// request.js文件
import axios from 'axios';
import qs from 'qs';
import { getToken } from './auth';
import { debounce } from './optimize';
import { baseURL } from '@/common/baseUrl.js';
// 把baseURL放到了公用变量里面，因为其它页面也有用到
// let baseURL = process.env.NODE_ENV === 'production' ? 'https://ttest.wanhuhealth.com' : 'https://ttest.wanhuhealth.com';
const service = axios.create({
  withCredentials: true,
  crossDomain: true,
  baseURL,
  timeout: 15000
});
const errorHandle = (status, other) => {
  switch (status) {
    case 1:
      uni.showToast({ title: '您还未登录，请登录', icon: 'none' });
      break;
    // 401: 未登录状态，跳转登录页
    case 401:
      wx.setStorageSync('token', '');
      toLogin();
      break;
    // 403 token过期
    case 403:
      uni.showToast({ title: '登录过期，请重新登录', icon: 'none' });
      setTimeout(() => {
        toLogin();
      }, 1000);
      break;
    // 404请求不存在
    case 404:
      // uni.showToast({ title: '请求的资源不存在', icon: 'none' });
      // 请求资源不存在，跳到全部服务页

      uni.showModal({
        title: '提示',
        content: '请求的资源不存在，请前往全部服务页',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: 'pages/index/index'
            });
          }
        }
      });
      break;
    case 500:
      uni.showToast({ title: '服务请求错误', icon: 'none' });
      break;
    case 501:
      uni.showToast({ title: '已被重定向', icon: 'none' });
      break;
    default:
      break;
  }
};
const toLogin = debounce(() => {
  uni.navigateTo({
    url: '/pages/join/index'
  });
}, 2000);
// request拦截器,在请求之前做一些处理
// const authorizeToken = 'aDU6UWQzdzBURmtBMVdZVzNCUg==';
service.interceptors.request.use(
  (config) => {
    // if (store.state.token) {
    //     // 给请求头添加user-token
    //     config.headers["user-token"] = store.state.token;
    // }
    // config.headers.Authorization = `Basic ${authorizeToken}`; // '7ab5c97f-c490-42f1-9e5b-df5657a61fbb'//
    // const includeUrlStr = ['getAppId', 'login', 'info', 'phone', 'getUser', 'patients', 'loginByUnionId'];
    if (!config.noAuth) {
      config.headers.Authorization = `Bearer ${getToken()}`;
    }
    if (!config.noqs) {
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  (error) => {
    // console.log(error); // for debug
    return Promise.reject(error);
  }
);

let count = -1;

axios.defaults.adapter = function (config) {
  // 自己定义个适配器，用来适配uniapp的语法
  return new Promise((resolve, reject) => {
    ++count;
    if (!count) {
      // uni.showToast({ title: '加载中', icon: 'loading', duration: 15000, mask: true });
    }

    let settle = require('axios/lib/core/settle');
    let buildURL = require('axios/lib/helpers/buildURL');
    uni.request({
      method: config.method.toUpperCase(),
      url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete: function complete(response) {
        response = {
          data: response.data,
          status: response.statusCode,
          errMsg: response.errMsg,
          header: response.header,
          config: config
        };
        if (response.statusCode !== 200) {
          errorHandle(response.status, response.errMsg);
        }
        settle(resolve, reject, response);
        --count;
        if (count === -1) {
          // setTimeout(() => {
          //   uni.hideToast();
          // }, 1000);
          // uni.showToast({ title: '加载中', icon: 'loading', mask: true });
        }
      }
    });
  });
};
// 配置成功后的拦截器
service.interceptors.response.use(
  (res) => {
    if (res.status === 200) {
      return res.data;
    } else {
      return Promise.reject(res);
    }
  },
  (error) => {
    const { response } = error;
    if (response) {
      errorHandle(response.status, response.data.message);
      return Promise.reject(response);
    }
    return false;
  }
);
export default service;
